package cn.itsource.pethome.user.interceptor;

import cn.itsource.pethome.basic.util.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.plaf.nimbus.State;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @description: 描述: 拦截器
 * @date: 2020/8/16 16:01
 * @author: summer
 * version: 1.0
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //获取请求头信息
        String header = request.getHeader("U-TOKEN");
        //判断是否为空 为空则证明未登录，不为空证明已登录
        if(StringUtils.isEmpty(header)){
            //调用 响应
            writeJson(response,0);
            return false;
        }
        //取出redis中的sessionid
        String userSession = RedisUtils.INSTANCE.get(header);
        //有新的请求       重新装入redis，生命周期延长30分钟
        RedisUtils.INSTANCE.set(header, userSession, 60*30);
        return true;
    }

    /**
     * 功能描述: 请求头中没有sessionid，响应给axios后置拦截器
     * @param response
     * @return: void
     * @Date: 2020/8/16
     */
    public void writeJson(HttpServletResponse response,Integer state){
        PrintWriter writer = null;
        try {
            //编码
            response.setContentType("text/json;charset=utf-8");
            //输出流
            writer = response.getWriter();
            //输出信息
            writer.write("{\"success\":false,\"msg\":\"noUser\"}"+"state");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(writer!= null){
                writer.close();
            }
        }
    }
}
